package org.linlinjava.litemall.admin.service;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Filter;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.admin.beans.FormulaConstants;
import org.linlinjava.litemall.admin.errorcode.ErrorCodeConstants;
import org.linlinjava.litemall.admin.vo.AdminLumiereMaterialClassificationVO;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallMerchandiseService;
import org.linlinjava.litemall.db.service.LumiereFormulaMaterialService;
import org.linlinjava.litemall.db.service.LumiereMaterialClassificationService;
import org.linlinjava.litemall.db.util.PageTools;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

import static org.linlinjava.litemall.core.exception.util.ServiceExceptionUtil.exception;

/**
 * @auth :ply
 * @date 2024/5/13 13:59
 * @Description TODO
 * 管理原料分类服务
 */
@Service
@RequiredArgsConstructor
public class AdminLumiereMaterialClassificationService {

    private final LumiereMaterialClassificationService lumiereMaterialClassificationService;

    private final LumiereFormulaMaterialService lumiereFormulaMaterialService;

    private final LitemallMerchandiseService litemallMerchandiseService;

//    public ResponseUtil.Response list(LumiereMaterialClassification lumiereMaterialClassification,
//                                                    @RequestParam(defaultValue = "1") Integer page,
//                                                    @RequestParam(defaultValue = "10") Integer limit){
//        PageHelper.offsetPage(limit,page-1);
//        LambdaQueryWrapper<LumiereMaterialClassification> queryWrapper = new LambdaQueryWrapper<>();
//
//        Optional.ofNullable(lumiereMaterialClassification.getClassificationName()).filter(StringUtils::isNotEmpty)
//                .ifPresent(name -> queryWrapper.like(LumiereMaterialClassification::getClassificationName, name));
//
//        List<LumiereMaterialClassification> list = lumiereMaterialClassificationService.list(queryWrapper);
//
//
//        return ResponseUtil.okPageInfo(null);
//    }

//    public ResponseUtil.Response list(AdminLumiereMaterialClassificationVO lumiereMaterialClassification,
//                                      @RequestParam(defaultValue = "1") Integer page,
//                                      @RequestParam(defaultValue = "10") Integer limit) throws InvocationTargetException, IllegalAccessException {
//        PageHelper.offsetPage(limit, page - 1);
//        LambdaQueryWrapper<LumiereMaterialClassification> queryWrapper = new LambdaQueryWrapper<>();
//
//        Optional.ofNullable(lumiereMaterialClassification.getClassificationName())
//                .filter(StringUtils::isNotEmpty)
//                .ifPresent(name -> queryWrapper.like(LumiereMaterialClassification::getClassificationName, name));
//        List<LumiereMaterialClassification> lumiereMaterialClassificationList  = lumiereMaterialClassificationService.list(queryWrapper);
//        List<AdminLumiereMaterialClassificationVO> list = new ArrayList<>();
//        for (LumiereMaterialClassification category : lumiereMaterialClassificationList) {
//            AdminLumiereMaterialClassificationVO categoryVO = new AdminLumiereMaterialClassificationVO();
//            BeanUtils.copyProperties(category,categoryVO);
//
//            List<AdminLumiereMaterialClassificationVO> children = new ArrayList<>();
////            List<LitemallCategory> subCategoryList = litemallCategoryService.queryByPid(category.getId());
//            List<LumiereMaterialClassification> subCategoryList = lumiereMaterialClassificationService.list(new LambdaQueryWrapper<LumiereMaterialClassification>().eq(LumiereMaterialClassification::getPid, category.getId()));
//            for (LumiereMaterialClassification subCategory : subCategoryList) {
//                AdminLumiereMaterialClassificationVO subCategoryVo =new AdminLumiereMaterialClassificationVO();
//                BeanUtils.copyProperties(subCategory,categoryVO);
//
//                List<AdminLumiereMaterialClassificationVO> childrenLThree = new ArrayList<>();
////                List<LitemallCategory> litemallCategories = litemallCategoryService.queryByPid(subCategory.getId());
//                List<LumiereMaterialClassification> litemallCategories = lumiereMaterialClassificationService.list(new LambdaQueryWrapper<LumiereMaterialClassification>().eq(LumiereMaterialClassification::getPid, category.getId()));
//                if(!CollectionUtils.isEmpty(litemallCategories)){
//                    for(LumiereMaterialClassification litemallCategory : litemallCategories){
//                        AdminLumiereMaterialClassificationVO categoryVoThree = new AdminLumiereMaterialClassificationVO();
//                        BeanUtils.copyProperties(litemallCategory,categoryVO);
//                        childrenLThree.add(categoryVoThree);
//                    }
//                }
//
//                subCategoryVo.setChildren(childrenLThree);
//                children.add(subCategoryVo);
//            }
//
//            categoryVO.setChildren(children);
//            list.add(categoryVO);
//        }
//
//        return ResponseUtil.okPageInfo(list);
//    }

//    public ResponseUtil.Response listLumiereMaterialClassifications(AdminLumiereMaterialClassificationVO classification,
//                                                                    @RequestParam(defaultValue = "1") Integer page,
//                                                                    @RequestParam(defaultValue = "10") Integer limit)
//            throws InvocationTargetException, IllegalAccessException {
//        // 分页查询
//        PageHelper.offsetPage(limit, page - 1);
//        // 构建查询条件
//        LambdaQueryWrapper<LumiereMaterialClassification> queryWrapper = new LambdaQueryWrapper<>();
//        Optional.ofNullable(classification.getClassificationName())
//                .filter(StringUtils::isNotEmpty)
//                .ifPresent(name -> queryWrapper.like(LumiereMaterialClassification::getClassificationName, name));
//
//        // 执行查询
//        List<LumiereMaterialClassification> classificationList = lumiereMaterialClassificationService.list(queryWrapper);
//
//        // 构建分类层级结构
//        List<AdminLumiereMaterialClassificationVO> resultList = buildCategoryHierarchy(classificationList, 0);
//
//        // 返回结果
//        return ResponseUtil.okPageInfo(resultList);
//    }
//
//    /**
//     * 递归构建分类层级结构
//     * @param classificationList 分类列表
//     * @param parentId 父分类ID
//     * @return 构建好的分类层级结构
//     */
//    private List<AdminLumiereMaterialClassificationVO> buildCategoryHierarchy(List<LumiereMaterialClassification> classificationList, Integer parentId) throws InvocationTargetException, IllegalAccessException {
//        List<AdminLumiereMaterialClassificationVO> resultList = new ArrayList<>();
//        for (LumiereMaterialClassification category : classificationList) {
//            if (category.getPid() != null && category.getPid().equals(parentId)) {
//                AdminLumiereMaterialClassificationVO categoryVO = new AdminLumiereMaterialClassificationVO();
//                BeanUtils.copyProperties(category, categoryVO);
//
//                // 递归构建子分类层级结构
//                List<AdminLumiereMaterialClassificationVO> childrenList = buildCategoryHierarchy(classificationList, category.getId());
//                categoryVO.setChildren(childrenList);
//
//                resultList.add(categoryVO);
//            }
//        }
//        return resultList;
//    }


//    public ResponseUtil.Response listLumiereMaterialClassifications(AdminLumiereMaterialClassificationVO classification,
//                                                                    @RequestParam(defaultValue = "1") Integer page,
//                                                                    @RequestParam(defaultValue = "10") Integer limit)
//            throws InvocationTargetException, IllegalAccessException {
//        // 分页查询
//        PageHelper.offsetPage(limit, page - 1);
//
//        // 构建查询条件
//        LambdaQueryWrapper<LumiereMaterialClassification> queryWrapper = new LambdaQueryWrapper<>();
//        Optional.ofNullable(classification.getClassificationName())
//                .filter(StringUtils::isNotEmpty)
//                .ifPresent(name -> queryWrapper.like(LumiereMaterialClassification::getClassificationName, name));
//
//        // 执行查询
//        List<LumiereMaterialClassification> classificationList = lumiereMaterialClassificationService.list(queryWrapper);
//
//        // 构建分类层级结构
//        List<AdminLumiereMaterialClassificationVO> resultList = buildClassificationHierarchy(classificationList);
//
//        // 返回结果
//        return ResponseUtil.okPageInfo(resultList);
//    }
//
//    /**
//     * 构建分类层级结构
//     * @param classificationList 分类列表
//     * @return 构建好的分类层级结构
//     */
//    private List<AdminLumiereMaterialClassificationVO> buildClassificationHierarchy(List<LumiereMaterialClassification> classificationList) throws InvocationTargetException, IllegalAccessException {
//        List<AdminLumiereMaterialClassificationVO> resultList = new ArrayList<>();
//
//        // 遍历分类列表
//        for (LumiereMaterialClassification classification : classificationList) {
//            // 创建当前分类对应的视图对象
//            AdminLumiereMaterialClassificationVO classificationVO = new AdminLumiereMaterialClassificationVO();
//            // 将分类对象的属性复制到视图对象中
//            BeanUtils.copyProperties(classification, classificationVO);
//
//            // 查询当前分类的子分类
//            List<LumiereMaterialClassification> subClassificationList = lumiereMaterialClassificationService
//                    .list(new LambdaQueryWrapper<LumiereMaterialClassification>()
//                            .eq(LumiereMaterialClassification::getPid, classification.getId()));
//
//            // 构建当前分类的子分类层级结构
//            List<AdminLumiereMaterialClassificationVO> childrenList = buildClassificationHierarchy(subClassificationList);
//            // 设置当前分类的子分类
//            classificationVO.setChildren(childrenList);
//
//            // 将当前分类视图对象添加到结果列表中
//            resultList.add(classificationVO);
//        }
//
//        return resultList;
//    }


    public ResponseUtil.Response listGroupBy() {
        List<LitemallMerchandise> merchandiseList = litemallMerchandiseService.selectList(Wrappers.lambdaQuery(LitemallMerchandise.class)
                .groupBy(LitemallMerchandise::getClassification)
                .orderByDesc(LitemallMerchandise::getAddTime));
        return ResponseUtil.ok(merchandiseList);
    }

    public ResponseUtil.Response listFormulaGroupBy() {
        /*List<LumiereFormulaMaterial> merchandiseList = lumiereFormulaMaterialService.list(Wrappers.lambdaQuery(LumiereFormulaMaterial.class)
                .groupBy(LumiereFormulaMaterial::getMaterialClassificationName)
                .orderByDesc(LumiereFormulaMaterial::getAddTime));*/

        List<LumiereMaterialClassification> materialClassificationList = lumiereMaterialClassificationService.list();
        return ResponseUtil.ok(materialClassificationList);
    }

    /**
     * 根据查询条件查询路米耶材料分类列表，并构建分类层级结构。
     * @param adminLumiereMaterialClassificationVO 查询条件
     * @param page 当前页数，默认为1
     * @param limit 每页数量，默认为10
     * @return 包含分类层级结构的响应结果
     * @throws InvocationTargetException 当调用目标方法异常时抛出
     * @throws IllegalAccessException 当访问类、字段、方法时发生异常时抛出
     */
    public ResponseUtil.Response listLumiereMaterialClassifications(AdminLumiereMaterialClassificationVO adminLumiereMaterialClassificationVO,
                                                                    @RequestParam(defaultValue = "1") Integer page,
                                                                    @RequestParam(defaultValue = "10") Integer limit)
    {
        // 分页查询
        //PageHelper.offsetPage(limit, page - 1);

        // 构建查询条件
        LambdaQueryWrapper<LumiereMaterialClassification> queryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(adminLumiereMaterialClassificationVO.getClassificationName())
                .filter(StringUtils::isNotEmpty)
                .ifPresent(name -> queryWrapper.like(LumiereMaterialClassification::getClassificationName, name));

        queryWrapper.orderByAsc(LumiereMaterialClassification::getNumber);

        // 执行查询
        List<LumiereMaterialClassification> classificationList = lumiereMaterialClassificationService.list(queryWrapper);

        // 构建分类层级结构
        List<AdminLumiereMaterialClassificationVO> resultList = new ArrayList<>();
        for (LumiereMaterialClassification classification : classificationList) {
            // 如果adminLumiereMaterialClassificationVO.getId()有值，则按照id和pid条件处理，否则只按pid判断
            if ((adminLumiereMaterialClassificationVO.getId() != null &&
                    classification.getId().equals(adminLumiereMaterialClassificationVO.getId()) &&
                    classification.getPid() == null) ||
                    (adminLumiereMaterialClassificationVO.getId() == null &&
                            classification.getPid() == null)) {

                AdminLumiereMaterialClassificationVO classificationVO = new AdminLumiereMaterialClassificationVO();
                BeanUtils.copyProperties(classification, classificationVO);

                // 构建子分类层级结构
                List<AdminLumiereMaterialClassificationVO> childrenList = buildClassificationHierarchy(classificationList, classification.getId());

                if (!childrenList.isEmpty()) {  // 仅在childrenList不为空时添加
                    classificationVO.setChildren(childrenList);
                }

                resultList.add(classificationVO);
            }
        }

        // 返回结果
        return ResponseUtil.ok(resultList);
    }

    public ResponseUtil.Response optionListLumiereMaterialClassifications() {
        // 构建查询条件
        LambdaQueryWrapper<LumiereMaterialClassification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(LumiereMaterialClassification::getPid);
        queryWrapper.orderByAsc(LumiereMaterialClassification::getNumber);

        // 执行查询
        List<LumiereMaterialClassification> classificationList = lumiereMaterialClassificationService.list(queryWrapper);
        // 返回结果
        return ResponseUtil.ok(classificationList);
    }

    /**
     * 递归构建分类层级结构
     * @param classificationList 分类列表
     * @param parentId 父分类ID
     * @return 构建好的分类层级结构
     */
    private List<AdminLumiereMaterialClassificationVO> buildClassificationHierarchy(List<LumiereMaterialClassification> classificationList, Integer parentId) {
        List<AdminLumiereMaterialClassificationVO> resultList = new ArrayList<>();
        for (LumiereMaterialClassification classification : classificationList) {
            if (classification.getPid() != null && classification.getPid().equals(parentId)) {
                AdminLumiereMaterialClassificationVO classificationVO = new AdminLumiereMaterialClassificationVO();
                BeanUtils.copyProperties(classification, classificationVO);
                List<AdminLumiereMaterialClassificationVO> childrenList = buildClassificationHierarchy(classificationList, classification.getId());
                if (!childrenList.isEmpty()) {  // 仅在childrenList不为空时添加
                    classificationVO.setChildren(childrenList);
                }
                resultList.add(classificationVO);
            }
        }
        return resultList;
    }

    /**
     * 根据指定ID获取原料分类详情。
     * @param id 原料分类ID
     * @return 包含原料分类详情的响应结果
     */
    public ResponseUtil.Response details(Integer id){
        return ResponseUtil.ok(lumiereMaterialClassificationService.getById(id));
    }

    /**
     * 添加新的原料分类。
     * @param lumiereMaterialClassification 待添加的原料分类对象
     * @return 添加操作的响应结果
     */
    public ResponseUtil.Response addLumiereMaterialClassification(LumiereMaterialClassification lumiereMaterialClassification) {
        List<LumiereMaterialClassification> list = lumiereMaterialClassificationService.list(null);
        // 使用Stream API检查是否存在相同名称的分类
        boolean exists = list.stream()
                .anyMatch(materialClassification ->
                        materialClassification.getClassificationName().equals(lumiereMaterialClassification.getClassificationName()));
        // 如果存在相同名称的分类，返回失败响应
        if (exists) {
            return ResponseUtil.fail(FormulaConstants.MATERIAL_CLASSIFICATION_NAME_EXISTING,"原料分类名称已存在");
        }
        return lumiereMaterialClassificationService.save(lumiereMaterialClassification) ? ResponseUtil.ok() : ResponseUtil.fail();
    }

    /**
     * 更新原料分类信息。
     * @param lumiereMaterialClassification 待更新的原料分类对象
     * @return 更新操作的响应结果
     */
    public ResponseUtil.Response updateLumiereMaterialClassification(LumiereMaterialClassification lumiereMaterialClassification) {
        List<LumiereMaterialClassification> list = lumiereMaterialClassificationService.list(null);
        // 使用Stream API检查是否存在相同名称的分类，排除当前对象本身
        boolean exists = list.stream()
                .anyMatch(materialClassification ->
                        !materialClassification.getId().equals(lumiereMaterialClassification.getId()) &&
                                materialClassification.getClassificationName().equals(lumiereMaterialClassification.getClassificationName()));
        // 如果存在相同名称的分类，返回失败响应
        if (exists) {
            return ResponseUtil.fail(FormulaConstants.MATERIAL_CLASSIFICATION_NAME_EXISTING,"原料分类名称已存在");
        }
        return lumiereMaterialClassificationService.updateById(lumiereMaterialClassification) ? ResponseUtil.ok() : ResponseUtil.fail();
    }

    /**
     * 根据指定ID删除原料分类。
     * @param id 待删除的路原料分类ID
     * @return 删除操作的响应结果
     */
    public ResponseUtil.Response deleteLumiereMaterialClassification(Integer id){
        List<LumiereMaterialClassification> list = lumiereMaterialClassificationService.list(new LambdaQueryWrapper<LumiereMaterialClassification>().eq(LumiereMaterialClassification::getPid, id));
        if (!list.isEmpty()) {
            return ResponseUtil.fail();
        }
        //查看引用
        List<LumiereFormulaMaterial> formulaMaterials = lumiereFormulaMaterialService.list(Wrappers.lambdaQuery(LumiereFormulaMaterial.class)
                .eq(LumiereFormulaMaterial::getMaterialClassificationId, id));
        if(formulaMaterials.size()>0){
            throw exception(ErrorCodeConstants.LUMIERE_FORMULA_FORMULA_MATERIAL_USE);
        }
        return lumiereMaterialClassificationService.removeById(id) ? ResponseUtil.ok() : ResponseUtil.fail();
    }


    @Transactional
    public ResponseUtil.Response syncLumiereMaterialClassifications() {
        // 获取所有原料
        List<LitemallMerchandise> merchandiseList = litemallMerchandiseService.selectList(Wrappers.lambdaQuery(LitemallMerchandise.class));
        Set<String> merchandiseNameList = CollStreamUtil.toSet(merchandiseList, LitemallMerchandise::getClassification);

        // 获取所有已存在的分类名称
        List<LumiereMaterialClassification> materialClassificationList = lumiereMaterialClassificationService.list();

        // 提取现有分类名称并转换为小写，去除空格
        Set<String> existingClassificationNames = materialClassificationList.stream()
                .map(classification -> classification.getClassificationName().trim().toLowerCase())  // 转为小写并去除空格
                .collect(Collectors.toSet());

        // 过滤出不在已有分类列表中的原料分类 (忽略大小写并去除空格)
        List<String> newMerchandiseList = merchandiseNameList.stream()
                .filter(classification -> !existingClassificationNames.contains(classification.trim().toLowerCase())) // 转为小写后比较并去除空格
                .collect(Collectors.toList());

        // 将新分类构建为 LumiereMaterialClassification 列表
        for (String classification : newMerchandiseList) {
            if(StrUtil.isEmpty(classification))continue;
            LumiereMaterialClassification lumiereMaterialClassification = new LumiereMaterialClassification()
                    .setClassificationName(classification)
                    .setNumber(1).setRemark("sync")
                    .setPid(null)
                    .setClassificationColour(getColor());
            lumiereMaterialClassificationService.save(lumiereMaterialClassification);
        }
        return ResponseUtil.ok(newMerchandiseList);
    }


    //随机生成颜色代码
    public String getColor(){
        //红色
        String red;
        //绿色
        String green;
        //蓝色
        String blue;
        //生成随机对象
        Random random = new Random();
        //生成红色颜色代码
        red = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成绿色颜色代码
        green = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成蓝色颜色代码
        blue = Integer.toHexString(random.nextInt(256)).toUpperCase();

        //判断红色代码的位数
        red = red.length()==1 ? "0" + red : red ;
        //判断绿色代码的位数
        green = green.length()==1 ? "0" + green : green ;
        //判断蓝色代码的位数
        blue = blue.length()==1 ? "0" + blue : blue ;
        //生成十六进制颜色值
        String color = "#"+red+green+blue;
        List<LumiereMaterialClassification> list = lumiereMaterialClassificationService.list(Wrappers.lambdaQuery(LumiereMaterialClassification.class)
                .eq(LumiereMaterialClassification::getClassificationColour, color));
        while (list.size()>0){
            color = getColor();
        }
        return color;
    }
}
